[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfoForEntity } from '@growi/core';
  5. import type {
  6. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  7. } from '@growi/core';
  8. import {
  9. isClient, pagePathUtils, pathUtils,
  10. } from '@growi/core/dist/utils';
  11. import ExtensibleCustomError from 'extensible-custom-error';
  12. import type {
  13. GetServerSideProps, GetServerSidePropsContext,
  14. } from 'next';
  15. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  16. import dynamic from 'next/dynamic';
  17. import Head from 'next/head';
  18. import { useRouter } from 'next/router';
  19. import superjson from 'superjson';
  20. import { useEditorModeClassName } from '~/client/services/layout';
  21. import { PageView } from '~/components/Page/PageView';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. import type { RendererConfig } from '~/interfaces/services/renderer';
  26. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  27. import type { PageModel, PageDocument } from '~/server/models/page';
  28. import type { PageRedirectModel } from '~/server/models/page-redirect';
  29. import {
  30. useCurrentUser,
  31. useIsForbidden, useIsSharedUser,
  32. useIsEnabledStaleNotification, useIsIdenticalPath,
  33. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  34. useDefaultIndentSize, useIsIndentSizeForced,
  35. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  36. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  37. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  38. useIsAllReplyShown, useIsContainerFluid, useIsNotCreatable,
  39. useIsUploadAllFileAllowed, useIsUploadEnabled,
  40. } from '~/stores/context';
  41. import { useEditingMarkdown } from '~/stores/editor';
  42. import {
  43. useSWRxCurrentPage, useSWRMUTxCurrentPage, useCurrentPageId,
  44. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  45. } from '~/stores/page';
  46. import { useRedirectFrom } from '~/stores/page-redirect';
  47. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  48. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  49. import loggerFactory from '~/utils/logger';
  50. import { BasicLayout } from '../components/Layout/BasicLayout';
  51. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  52. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  53. import type { NextPageWithLayout } from './_app.page';
  54. import type { CommonProps } from './utils/commons';
  55. import {
  56. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  57. } from './utils/commons';
  58. declare global {
  59. // eslint-disable-next-line vars-on-top, no-var
  60. var globalEmitter: EventEmitter;
  61. }
  62. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  63. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  64. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  65. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  66. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  67. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  68. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  69. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  70. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  71. const TagEditModal = dynamic(() => import('../components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  72. const ConflictDiffModal = dynamic(() => import('../components/PageEditor/ConflictDiffModal').then(mod => mod.ConflictDiffModal), { ssr: false });
  73. const logger = loggerFactory('growi:pages:all');
  74. const {
  75. isPermalink: _isPermalink, isCreatablePage,
  76. } = pagePathUtils;
  77. const { removeHeadingSlash } = pathUtils;
  78. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  79. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  80. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  81. {
  82. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  83. return v?.data != null
  84. && v?.data.toObject != null
  85. && v?.meta != null
  86. && isIPageInfoForEntity(v.meta);
  87. },
  88. serialize: (v) => {
  89. return {
  90. data: superjson.stringify(v.data.toObject()),
  91. meta: superjson.stringify(v.meta),
  92. };
  93. },
  94. deserialize: (v) => {
  95. return {
  96. data: superjson.parse(v.data),
  97. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  98. };
  99. },
  100. },
  101. 'IPageToShowRevisionWithMetaTransformer',
  102. );
  103. // GrowiContextualSubNavigation for NOT shared page
  104. type GrowiContextualSubNavigationProps = {
  105. isLinkSharingDisabled: boolean,
  106. }
  107. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  108. const { isLinkSharingDisabled } = props;
  109. const { data: currentPage } = useSWRxCurrentPage();
  110. return (
  111. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  112. );
  113. };
  114. type Props = CommonProps & {
  115. pageWithMeta: IPageToShowRevisionWithMeta | null,
  116. // pageUser?: any,
  117. redirectFrom?: string;
  118. // shareLinkId?: string;
  119. isLatestRevision?: boolean,
  120. isIdenticalPathPage?: boolean,
  121. isForbidden: boolean,
  122. isNotFound: boolean,
  123. isNotCreatable: boolean,
  124. // isAbleToDeleteCompletely: boolean,
  125. templateTagData?: string[],
  126. templateBodyData?: string,
  127. isSearchServiceConfigured: boolean,
  128. isSearchServiceReachable: boolean,
  129. isSearchScopeChildrenAsDefault: boolean,
  130. isEnabledMarp: boolean,
  131. sidebarConfig: ISidebarConfig,
  132. isSlackConfigured: boolean,
  133. // isMailerSetup: boolean,
  134. isAclEnabled: boolean,
  135. // hasSlackConfig: boolean,
  136. drawioUri: string | null,
  137. noCdn: string,
  138. // highlightJsStyle: string,
  139. isAllReplyShown: boolean,
  140. isContainerFluid: boolean,
  141. isUploadEnabled: boolean,
  142. isUploadAllFileAllowed: boolean,
  143. isEnabledStaleNotification: boolean,
  144. isEnabledAttachTitleHeader: boolean,
  145. // isEnabledLinebreaks: boolean,
  146. // isEnabledLinebreaksInComments: boolean,
  147. adminPreferredIndentSize: number,
  148. isIndentSizeForced: boolean,
  149. disableLinkSharing: boolean,
  150. skipSSR: boolean,
  151. ssrMaxRevisionBodyLength: number,
  152. rendererConfig: RendererConfig,
  153. };
  154. const Page: NextPageWithLayout<Props> = (props: Props) => {
  155. // register global EventEmitter
  156. if (isClient() && window.globalEmitter == null) {
  157. window.globalEmitter = new EventEmitter();
  158. }
  159. const router = useRouter();
  160. useCurrentUser(props.currentUser ?? null);
  161. // commons
  162. useCsrfToken(props.csrfToken);
  163. useGrowiCloudUri(props.growiCloudUri);
  164. // page
  165. useIsContainerFluid(props.isContainerFluid);
  166. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  167. useIsForbidden(props.isForbidden);
  168. useIsNotCreatable(props.isNotCreatable);
  169. useRedirectFrom(props.redirectFrom ?? null);
  170. useIsSharedUser(false); // this page cann't be routed for '/share'
  171. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  172. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  173. useIsSearchPage(false);
  174. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  175. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  176. useIsSearchServiceReachable(props.isSearchServiceReachable);
  177. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  178. useIsSlackConfigured(props.isSlackConfigured);
  179. // useIsMailerSetup(props.isMailerSetup);
  180. useIsAclEnabled(props.isAclEnabled);
  181. // useHasSlackConfig(props.hasSlackConfig);
  182. // useNoCdn(props.noCdn);
  183. useDefaultIndentSize(props.adminPreferredIndentSize);
  184. useIsIndentSizeForced(props.isIndentSizeForced);
  185. useDisableLinkSharing(props.disableLinkSharing);
  186. useRendererConfig(props.rendererConfig);
  187. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  188. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  189. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  190. useIsAllReplyShown(props.isAllReplyShown);
  191. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  192. useIsUploadEnabled(props.isUploadEnabled);
  193. const { pageWithMeta } = props;
  194. const pageId = pageWithMeta?.data._id;
  195. const revisionBody = pageWithMeta?.data.revision?.body;
  196. useCurrentPathname(props.currentPathname);
  197. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  198. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  199. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  200. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  201. const { mutate: mutateIsNotFound } = useIsNotFound();
  202. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  203. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  204. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  205. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  206. useSetupGlobalSocket();
  207. useSetupGlobalSocketForPage(pageId);
  208. // Store initial data (When revisionBody is not SSR)
  209. useEffect(() => {
  210. if (!props.skipSSR) {
  211. return;
  212. }
  213. if (currentPageId != null && !props.isNotFound) {
  214. const mutatePageData = async() => {
  215. const pageData = await mutateCurrentPage();
  216. mutateEditingMarkdown(pageData?.revision?.body);
  217. };
  218. // If skipSSR is true, use the API to retrieve page data.
  219. // Because pageWIthMeta does not contain revision.body
  220. mutatePageData();
  221. }
  222. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  223. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  224. useEffect(() => {
  225. const decodedURI = decodeURI(window.location.pathname);
  226. if (isClient() && decodedURI !== props.currentPathname) {
  227. const { search, hash } = window.location;
  228. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  229. }
  230. }, [props.currentPathname, router]);
  231. // initialize mutateEditingMarkdown only once per page
  232. // need to include useCurrentPathname not useCurrentPagePath
  233. useEffect(() => {
  234. if (props.currentPathname != null) {
  235. mutateEditingMarkdown(revisionBody);
  236. }
  237. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  238. useEffect(() => {
  239. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  240. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  241. useEffect(() => {
  242. mutateCurrentPageId(pageId ?? null);
  243. }, [mutateCurrentPageId, pageId]);
  244. useEffect(() => {
  245. mutateIsNotFound(props.isNotFound);
  246. }, [mutateIsNotFound, props.isNotFound]);
  247. useEffect(() => {
  248. mutateIsLatestRevision(props.isLatestRevision);
  249. }, [mutateIsLatestRevision, props.isLatestRevision]);
  250. useEffect(() => {
  251. mutateTemplateTagData(props.templateTagData);
  252. }, [props.templateTagData, mutateTemplateTagData]);
  253. useEffect(() => {
  254. mutateTemplateBodyData(props.templateBodyData);
  255. }, [props.templateBodyData, mutateTemplateBodyData]);
  256. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  257. // So preferentially take page data from useSWRxCurrentPage
  258. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  259. const title = generateCustomTitleForPage(props, pagePath);
  260. return (
  261. <>
  262. <Head>
  263. <title>{title}</title>
  264. </Head>
  265. <div className="dynamic-layout-root justify-content-between">
  266. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  267. <DisplaySwitcher
  268. pageView={(
  269. <PageView
  270. pagePath={pagePath}
  271. initialPage={pageWithMeta?.data}
  272. rendererConfig={props.rendererConfig}
  273. />
  274. )}
  275. />
  276. <PageStatusAlert />
  277. </div>
  278. </>
  279. );
  280. };
  281. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  282. const editorModeClassName = useEditorModeClassName();
  283. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  284. };
  285. type LayoutProps = Props & {
  286. children?: ReactNode
  287. }
  288. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  289. // init sidebar config with UserUISettings and sidebarConfig
  290. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  291. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  292. };
  293. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  294. return (
  295. <>
  296. <GrowiPluginsActivator />
  297. <DrawioViewerScript />
  298. <Layout {...page.props}>
  299. {page}
  300. </Layout>
  301. <UnsavedAlertDialog />
  302. <DescendantsPageListModal />
  303. <DrawioModal />
  304. <HandsontableModal />
  305. <QuestionnaireModalManager />
  306. <TemplateModal />
  307. <LinkEditModal />
  308. <TagEditModal />
  309. <ConflictDiffModal />
  310. </>
  311. );
  312. };
  313. function getPageIdFromPathname(currentPathname: string): string | null {
  314. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  315. }
  316. class MultiplePagesHitsError extends ExtensibleCustomError {
  317. pagePath: string;
  318. constructor(pagePath: string) {
  319. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  320. this.pagePath = pagePath;
  321. }
  322. }
  323. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  324. const { model: mongooseModel } = await import('mongoose');
  325. const req: CrowiRequest = context.req as CrowiRequest;
  326. const { crowi } = req;
  327. const { revisionId } = req.query;
  328. const Page = crowi.model('Page') as PageModel;
  329. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  330. const { pageService, configManager } = crowi;
  331. let currentPathname = props.currentPathname;
  332. const pageId = getPageIdFromPathname(currentPathname);
  333. const isPermalink = _isPermalink(currentPathname);
  334. const { user } = req;
  335. if (!isPermalink) {
  336. // check redirects
  337. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  338. if (chains != null) {
  339. // overwrite currentPathname
  340. currentPathname = chains.end.toPath;
  341. props.currentPathname = currentPathname;
  342. // set redirectFrom
  343. props.redirectFrom = chains.start.fromPath;
  344. }
  345. // check whether the specified page path hits to multiple pages
  346. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  347. if (count > 1) {
  348. throw new MultiplePagesHitsError(currentPathname);
  349. }
  350. }
  351. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  352. const page = pageWithMeta?.data as unknown as PageDocument;
  353. // add user to seen users
  354. if (page != null && user != null) {
  355. await page.seen(user);
  356. }
  357. // populate & check if the revision is latest
  358. if (page != null) {
  359. page.initLatestRevisionField(revisionId);
  360. props.isLatestRevision = page.isLatestRevision();
  361. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  362. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  363. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  364. }
  365. props.pageWithMeta = pageWithMeta;
  366. }
  367. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  368. const req: CrowiRequest = context.req as CrowiRequest;
  369. const { crowi } = req;
  370. const Page = crowi.model('Page') as PageModel;
  371. const { currentPathname } = props;
  372. const pageId = getPageIdFromPathname(currentPathname);
  373. const isPermalink = _isPermalink(currentPathname);
  374. const page = props.pageWithMeta?.data;
  375. if (props.isIdenticalPathPage) {
  376. props.isNotCreatable = true;
  377. }
  378. else if (page == null) {
  379. props.isNotFound = true;
  380. props.isNotCreatable = !isCreatablePage(currentPathname);
  381. // check the page is forbidden or just does not exist.
  382. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  383. props.isForbidden = count > 0;
  384. }
  385. else {
  386. props.isNotFound = page.isEmpty;
  387. props.isNotCreatable = false;
  388. props.isForbidden = false;
  389. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  390. if (isPermalink && page.isEmpty) {
  391. props.currentPathname = page.path;
  392. }
  393. // /path/to/page ==> /62a88db47fed8b2d94f30000
  394. if (!isPermalink && !page.isEmpty) {
  395. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  396. if (!isToppage) {
  397. props.currentPathname = `/${page._id}`;
  398. }
  399. }
  400. }
  401. }
  402. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  403. // const req: CrowiRequest = context.req as CrowiRequest;
  404. // const { crowi } = req;
  405. // const UserModel = crowi.model('User');
  406. // if (isUserPage(props.currentPagePath)) {
  407. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  408. // if (user != null) {
  409. // props.pageUser = JSON.stringify(user.toObject());
  410. // }
  411. // }
  412. // }
  413. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  414. const req: CrowiRequest = context.req as CrowiRequest;
  415. const { crowi } = req;
  416. const {
  417. searchService, configManager, aclService,
  418. } = crowi;
  419. props.isSearchServiceConfigured = searchService.isConfigured;
  420. props.isSearchServiceReachable = searchService.isReachable;
  421. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  422. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  423. // props.isMailerSetup = mailService.isMailerSetup;
  424. props.isAclEnabled = aclService.isAclEnabled();
  425. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  426. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  427. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  428. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  429. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  430. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  431. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  432. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  433. props.isUploadAllFileAllowed = crowi.fileUploadService.getFileUploadEnabled();
  434. props.isUploadEnabled = crowi.fileUploadService.getIsUploadable();
  435. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  436. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  437. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  438. props.sidebarConfig = {
  439. isSidebarCollapsedMode: configManager.getConfig('crowi', 'customize:isSidebarCollapsedMode'),
  440. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  441. };
  442. props.rendererConfig = {
  443. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  444. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  445. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  446. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  447. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  448. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  449. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  450. // XSS Options
  451. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  452. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  453. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  454. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  455. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  456. };
  457. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  458. }
  459. /**
  460. * for Server Side Translations
  461. * @param context
  462. * @param props
  463. * @param namespacesRequired
  464. */
  465. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  466. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  467. props._nextI18Next = nextI18NextConfig._nextI18Next;
  468. }
  469. const getAction = (props: Props): SupportedActionType => {
  470. if (props.isNotCreatable) {
  471. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  472. }
  473. if (props.isForbidden) {
  474. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  475. }
  476. if (props.isNotFound) {
  477. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  478. }
  479. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  480. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  481. }
  482. return SupportedAction.ACTION_PAGE_VIEW;
  483. };
  484. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  485. const req = context.req as CrowiRequest;
  486. const { user } = req;
  487. const result = await getServerSideCommonProps(context);
  488. // check for presence
  489. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  490. if (!('props' in result)) {
  491. throw new Error('invalid getSSP result');
  492. }
  493. const props: Props = result.props as Props;
  494. if (props.redirectDestination != null) {
  495. return {
  496. redirect: {
  497. permanent: false,
  498. destination: props.redirectDestination,
  499. },
  500. };
  501. }
  502. if (user != null) {
  503. props.currentUser = user.toObject();
  504. }
  505. try {
  506. await injectPageData(context, props);
  507. }
  508. catch (err) {
  509. if (err instanceof MultiplePagesHitsError) {
  510. props.isIdenticalPathPage = true;
  511. }
  512. else {
  513. throw err;
  514. }
  515. }
  516. await injectRoutingInformation(context, props);
  517. injectServerConfigurations(context, props);
  518. await injectNextI18NextConfigurations(context, props, ['translation']);
  519. addActivity(context, getAction(props));
  520. return {
  521. props,
  522. };
  523. };
  524. export default Page;